﻿using System;

namespace Sentient.Core
{
    public abstract class IdentityFieldProvider<T> : IEquatable<IdentityFieldProvider<T>>
    {
        public abstract T TransientValue();

        private int? _oldHashCode;
        
        private T _id;

        public virtual T Id
        {
            get { return _id; }
            set { _id = value; }
        }


        public override bool Equals(object obj)
        {
            var other = obj as IdentityFieldProvider<T>;
            if (other == null)
                return false;

            return Equals(other);
        }

        public bool Equals(IdentityFieldProvider<T> other)
        {
            // handle the case of comparing two NEW objects
            var otherIsTransient = Equals(other.Id, TransientValue());
            var thisIsTransient = Equals(Id, TransientValue());

            if (otherIsTransient && thisIsTransient)
                return ReferenceEquals(other, this);

            return other.Id.Equals(Id);
        }

        public override int GetHashCode()
        {
            // Once we have a hash code we'll never change it
            if (_oldHashCode.HasValue)
                return _oldHashCode.Value;

            var thisIsTransient = Equals(Id, Guid.Empty);

            // When this instance is transient, we use the base GetHashCode()
            // and remember it, so an instance can NEVER change its hash code.
            if (thisIsTransient)
            {
                _oldHashCode = base.GetHashCode();
                return _oldHashCode.Value;
            }

            return Id.GetHashCode();
        }


        public static bool operator ==(IdentityFieldProvider<T> x, IdentityFieldProvider<T> y)
        {
            return Equals(x, y);
        }

        public static bool operator !=(IdentityFieldProvider<T> x, IdentityFieldProvider<T> y)
        {
            return !(x == y);
        }
    }

    public class GuidIdentityFieldProvider : IdentityFieldProvider<Guid>
    {
        public override Guid TransientValue()
        {
            return Guid.Empty;
        }
    }

    public class IntIdentityFieldProvider : IdentityFieldProvider<int>
    {
        public override int TransientValue()
        {
            return 0;
        }
    }
}